import { WorksItem } from '@/pages/pc/components/Works';
import CheckTag from '@/pages/pc/components/CheckTag';
import Pagination from '@/pages/pc/components/Pagination';
import styles from './index.less';
import { useState, useEffect, useRef } from 'react';
import { Link, useHistory, Helmet } from 'umi';
import { allGet } from '@/services/pc';
import qs from 'qs';
import Empty from '@/pages/pc/components/Empty';
import VideoPlayerModal from '../components/VideoPlayer';
import { message, Select, Skeleton } from 'antd';
import WorkDetailModal, { WorkDetailModalRef } from '@/pages/pc/components/WorkDetailModal';

const score = [
  { label: '全部', value: '' },
  { label: 'S', value: '4' },
  { label: 'A+', value: '3' },
  // { label: 'A', value: '2' },
  // { label: 'B', value: '1' },
];
const order = [
  { label: '最新', value: 'bid' },
  { label: '推荐', value: 'rand' },
  { label: '全部', value: '' },
];

const pageSize = 20;
const Index = (props) => {
  const { query = {}, search, match } = props;
  const history = useHistory();
  const [loading, setLoading] = useState(true);
  const workDetailModalRef = useRef<WorkDetailModalRef>(null);
  console.log(props.initialPropsOk, '222');
  useEffect(() => {
    if (props.initialPropsOk) {
      // setLoading(false);
    }
  }, [props.initialPropsOk]);

  // 分类
  const [column, setColumn] = useState<any>([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({
        params: { mod: 'course', do: 'category', version: 'pc1.0' },
      });
      const arr: any[] = [];
      response?.data?.forEach((item) => {
        if (item.cid !== '70' && item.cid !== '36') {
          arr.push({ label: item.name, value: item.cid });
        }
      });
      arr.unshift({ label: '全部', value: '' });
      // const arr: any[] =
      //   (response?.data?.map((item) => ({ label: item.name, value: item.cid })) || []).filter(item => item.value !== 70 && item.value !== 36);

      setColumn(arr);
    })();
  }, []);

  // 客户端同步
  useEffect(() => {
    if (!props.isServer) {
      // setData(props.data ?? []);
    }
  }, [props.initialPropsOk, props.isServer]);

  const handleChangeSearch = (key, value) => {
    const newQuery = query;
    newQuery[key] = value?.[0];
    const string = qs.stringify(query);

    history.push(`/works/${1}?${string}`);
  };
  const itemRender = (current, type, originalElement) => {
    if (type === 'page') {
      return <Link to={`/works/${current}${search}`}>{current}</Link>;
    }
    if (type === 'next') {
      return <Link to={`/works/${current}${search}`}>{originalElement}</Link>;
    }
    if (type === 'prev') {
      return <Link to={`/works/${current}${search}`}>{originalElement}</Link>;
    }

    return originalElement;
  };
  const handleItemClick = (index, e) => {
    workDetailModalRef.current?.show({
      ids: props?.works?.data?.list?.map((item) => item.bid),
      currentId: props?.works?.data?.list?.[index]?.bid,
    });
    // VideoPlayerModal.showStar({
    //   data:
    //     props?.works?.data?.list?.map((item) => ({ ...item, url: item.video || item.pic })) || [],
    //   defaultIndex: index,
    // });
  };

  const currentPage = parseInt(match?.params?.page);
  const handleDeleteOK = (item) => {
    message.success('删除成功');
    const newQuery = { ...query, t: Date.now() };
    const string = qs.stringify(newQuery);
    history.push(`/works/${currentPage}?${string}`);
  };
  return (
    <div className={styles.page}>
      <Helmet>
        <title>全部 - 学员作品 - CGJOY课堂</title>
        <meta name="title" content="全部 - 学员作品 - CGJOY课堂" />
        <meta name="keywords" content={props.keywords} />
        <meta name="description" content={props.description} />
      </Helmet>
      <div className={styles.header}>
        <div className={styles.row}>
          <div className={styles.rowitem}>
            <div className={styles.key}>排序：</div>
            <CheckTag
              data={order}
              key={query.order}
              defaultValue={[query.order || '']}
              onChange={(value) => handleChangeSearch('order', value)}
            />
          </div>
          <div className={styles.rowitem}>
            <div className={styles.key}>评级：</div>
            <Select
              className={styles.select}
              options={score}
              key={query.score}
              defaultValue={query.score || ''}
              dropdownMatchSelectWidth={false}
              onChange={(value) => handleChangeSearch('score', value)}
            />
          </div>
          <div className={styles.rowitem}>
            <div className={styles.key}>分类：</div>
            <Select
              className={styles.select}
              options={column}
              key={query.score}
              dropdownMatchSelectWidth={false}
              defaultValue={query.cid || ''}
              onChange={(value) => handleChangeSearch('cid', value)}
            />
          </div>
        </div>
      </div>
      <div className={styles.main}>
        <div className={styles.list}>
          {props?.works?.data?.list?.length > 0 ? (
            props?.works?.data?.list?.map((item, index) => (
              // eslint-disable-next-line react/jsx-key
              <div className={styles.item}>
                <WorksItem
                  onClick={handleItemClick}
                  isLink={false}
                  hasAdminAction
                  itemType={4}
                  type={item.video ? 'video' : 'img'}
                  index={index}
                  handleDeleteOK={handleDeleteOK}
                  {...item}
                />
              </div>
            ))
          ) : props.initialPropsOk ? (
            <Empty />
          ) : (
            <div
              style={{
                display: 'grid',
                width: '100%',
                gridTemplateColumns: '1fr 1fr 1fr 1fr',
                gap: 20,
              }}
            >
              {new Array(20).fill(1).map((num, index) => (
                <Skeleton key={index + num} active />
              ))}
            </div>
          )}
        </div>
      </div>
      {(props?.works?.data?.count > pageSize || currentPage != 1) && (
        <Pagination
          pageSize={pageSize}
          itemRender={itemRender}
          className={styles.pagination}
          total={props?.works?.data?.count}
          current={currentPage}
        />
      )}
      <WorkDetailModal ref={workDetailModalRef} />
    </div>
  );
};

function getRandomElementsByIndices(array, count) {
  if (array.length < count) {
    throw new Error('数组长度不足');
  }

  const indices = [];
  const result = [];
  const usedIndices = new Set();

  while (indices.length < count) {
    const randomIndex = Math.floor(Math.random() * array.length);
    if (!usedIndices.has(randomIndex)) {
      indices.push(randomIndex);
      usedIndices.add(randomIndex);
      result.push(array[randomIndex]);
    }
  }

  return result;
}

Index.getInitialProps = async ({ match, history, isServer }) => {
  const { query, search } = history?.location || {};

  const params: any = {
    mod: 'busywork',
    do: 'list',
    perpage: pageSize,
    page: match?.params?.page,
    version: 'pc1.0',
  };
  if (query.cid) {
    params.cid = query.cid;
  }
  if (query.order) {
    params.order = query.order;
  }
  if (query.score) {
    params.score = query.score;
  }
  const [works, columnResponse] = await Promise.all([
    allGet({ params }),
    allGet({
      params: { mod: 'course', do: 'category', version: 'pc1.0' },
    }),
  ]);
  const keywords = (columnResponse.data?.map?.((item) => item.name + '作品') || []).join(',');
  const description = (
    works?.data?.list?.map?.((item) => item.username + '作品：' + item.classname) || []
  )
    .join(',')
    .slice(0, 100);

  if (works?.data?.list.length > 18 && Array.isArray(works.data.list)) {
    const randomElements = getRandomElementsByIndices(works.data.list, 24 - works.data.list.length);
    works.data.list = [...works.data.list, ...randomElements];
  }
  return {
    initialPropsOk: true,
    works,
    match,
    query,
    search,
    isServer,
    keywords,
    description,
  };
};
export default Index;
